package frame

import (
	"gitee.com/lipore/go-nio/pkg/buffer"
	"gitee.com/lipore/plume/logger"
)

type fixedLengthFrameCodec struct {
	length int
	fill   byte
}

func (c *fixedLengthFrameCodec) Decode(buffer *buffer.Buffer) (Frame, bool, error) {
	if buffer.Len() >= c.length {
		f := make([]byte, c.length)
		n, err := buffer.Read(f)
		if n != c.length {
			logger.Warnf("fixedLengthFrameCodec: decode failed, read %d, read error: %v", n, err)
			return nil, false, nil
		}
		if err != nil {
			return nil, false, err
		}
		return f, true, nil
	}
	return nil, false, nil
}

func (c *fixedLengthFrameCodec) Encode(f Frame) ([]byte, bool) {
	if len(f) > c.length {
		r := make([]byte, c.length*(len(f)/c.length))
		copy(r, f)
		return r, true
	} else {
		r := make([]byte, c.length)
		copy(r, f)
		return r, true
	}
}

func FixedLengthFrameCodec(length int, fill byte) CodeC {
	return &fixedLengthFrameCodec{
		length: length,
		fill:   fill,
	}
}
